import tinymce from 'tinymce/tinymce'
import store from '@/store'
import { sleep } from '@/utils/helpers'

/**
 * 1. 通过术语弹窗插入或管理
 * 2. 通过按 backspace 或 delete 按键删除
 * 3. 设置了页面的其他条标题
 */
export default function (editor) {
  editor.on('termsUpdated', async () => {
    await sleep()
    const termsIndex = 'item' + getTitleNode()?.dataset?.index?.split('.').length
    editor.dom.select('[data-content-page-type="terms_definitions"] .term-block p.list-title').forEach((node) => {
      editor.dom.setAttrib(node, 'data-type', termsIndex)
    })
    store.commit('xmleditor/UPDATE_DOC_STRUCTURE')
  })
}

function getTitleNode() {
  const selector = '.list-title:not(.term-block p)'
  const { is, select, getPrev } = tinymce.activeEditor.dom
  let currentNode = null
  const blocks = select('#tinymce>.page-wrapper [data-content-page-type="terms_definitions"] .term-block')

  // 如果已经存在术语，则直接依据第一个术语前的条标题
  if (blocks?.length) {
    currentNode = blocks[0]
  } else {
    // 如果没有术语，则以光标所在位置
    currentNode = tinymce.activeEditor.selection.getNode()
    // 如果当前光标在标题节点，则以该条标题
    if (is(currentNode, selector)) return currentNode
  }

  if (!currentNode) {
    console.warn('===术语序号计算异常===')
    return null
  }

  // 如果当前层级有前个是条标题节点，则直接返回
  let titleNode = getPrev(currentNode, selector)
  if (titleNode) {
    return titleNode
  }

  function myGetPrev(node) {
    if (node === null) return null
    const parentNode = node.parentNode

    if (is(parentNode, selector)) {
      return parentNode
    }

    const parentPrev = getPrev(parentNode, selector)
    if (parentPrev) {
      return parentPrev
    }

    return myGetPrev(parentNode)
  }

  return myGetPrev(currentNode)
}
